package wfl.spec.edu;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ActivityLogin extends AppCompatActivity {
    private String TAG;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginlayout);
    }
    public void login(View v){
        //拼接请求url
        EditText etNumber =findViewById(R.id.student_number);
        String studentNumber=etNumber.getText().toString();
        EditText etPwd=findViewById(R.id.password);
        String password=etPwd.getText().toString();
        final String url="http://www.yyjsx.xyz/api/student/login?studentNumber="+studentNumber+"&password="+password;
        //发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient();
                Request request=new Request.Builder().url(url).build();
                try{
                    Response response=client.newCall(request).execute();
                    String responseStr=response.body().string();
                    //解析网络请求
                    //Log.d(TAG, "login: "+responseStr);
                    JSONObject jsonObject=new JSONObject(responseStr);
                    final Boolean success=jsonObject.getBoolean("success");
                    final String message=jsonObject.getString("message");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(success==true){
                                Intent intent=new Intent(ActivityLogin.this,MainActivity.class);
                                startActivity(intent);
                            }
                            else{
                                Toast.makeText(ActivityLogin.this,message,Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
